﻿using System;
using System.ComponentModel;

namespace Easycmd
{
    public interface ThreadWorkerHost
    {
        void ProgressChanged(int percent);
        void RunProc(ThreadWorker worker);
        void Completed(bool isCancel);

        void Progress2(int MaxProgress, int Step);
    }
    public class ThreadWorker
    {
        BackgroundWorker innerWorker = new BackgroundWorker();
        ThreadWorkerHost sink;
        bool CompletedByCancel = false;
        int FileCount = 0;
        public ThreadWorker(ThreadWorkerHost sink,int fileCount)
        {
            FileCount = fileCount;
            this.sink = sink;
            innerWorker.DoWork += new DoWorkEventHandler(worker_DoWork);
            innerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            innerWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            innerWorker.WorkerSupportsCancellation = true;
            innerWorker.WorkerReportsProgress = true;
        }
        public void Run()
        {
            
            innerWorker.RunWorkerAsync();
        }
        public void Cancel()
        {
            innerWorker.CancelAsync();
            CompletedByCancel = true;
        }
        public bool IsCanceling()
        {
            return innerWorker.CancellationPending;
        }
        public void Progress(int percent)
        {
            innerWorker.ReportProgress(percent);
        }
        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            sink.ProgressChanged(e.ProgressPercentage);
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            sink.Completed(CompletedByCancel);
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            sink.RunProc(this);
        }

        internal void Progress2(int MaxProgress, int Step)
        {
            //sink.Progress2(MaxProgress, Step);
        }
    }
}
